package com.mldong.flow.engine.cfg;


import cn.hutool.db.DbUtil;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.mldong.flow.engine.Context;
import com.mldong.flow.engine.core.ServiceContext;
import com.mldong.flow.engine.impl.SimpleContext;
import com.mldong.flow.engine.mapper.ProcessDefineMapper;
import com.mldong.flow.engine.mapper.ProcessInstanceMapper;
import com.mldong.flow.engine.mapper.ProcessTaskActorMapper;
import com.mldong.flow.engine.mapper.ProcessTaskMapper;
import com.mldong.flow.engine.parser.impl.*;
import com.mldong.flow.engine.service.impl.ProcessDefineServiceImpl;
import com.mldong.flow.engine.service.impl.ProcessInstanceServiceImpl;
import com.mldong.flow.engine.service.impl.ProcessTaskServiceImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
/**
 *
 * 流程引擎配置类
 * @author mldong
 * @date 2022/6/12
 */
public class Configuration {
    public Configuration() {
        this(new SimpleContext());
    }
    public Configuration(Context context) {
        ServiceContext.setContext(context);
        ServiceContext.put("decision", DecisionParser.class);
        ServiceContext.put("end", EndParser.class);
        ServiceContext.put("fork", ForkParser.class);
        ServiceContext.put("join", JoinParser.class);
        ServiceContext.put("start", StartParser.class);
        ServiceContext.put("task", TaskParser.class);
        SqlSessionFactory sqlSessionFactory = initSqlSessionFactory();
        ServiceContext.put("sqlSessionFactory",sqlSessionFactory);
        ServiceContext.put("processDefineService",new ProcessDefineServiceImpl(sqlSessionFactory));
        ServiceContext.put("processInstanceService",new ProcessInstanceServiceImpl(sqlSessionFactory));
        ServiceContext.put("processTaskService",new ProcessTaskServiceImpl(sqlSessionFactory));

    }
    //工厂方法
    public static SqlSessionFactory initSqlSessionFactory() {
        DataSource dataSource = DbUtil.getDs();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("FLOW", transactionFactory, dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration(environment);
        //在这里添加Mapper
        configuration.addMapper(ProcessDefineMapper.class);
        configuration.addMapper(ProcessInstanceMapper.class);
        configuration.addMapper(ProcessTaskMapper.class);
        configuration.addMapper(ProcessTaskActorMapper.class);
        return new MybatisSqlSessionFactoryBuilder().build(configuration);
    }
}
